{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 在 Paddle Quantum 中模拟含噪量子电路\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 噪声简介\n",
    "\n",
    "在理想模型中，我们通常假设量子电路是在一个**封闭系统**中执行的。然而在真实的量子设备中，系统会通过和环境的相互作用产生**非相干噪声（incoherent noise）**。在近期的量子设备上，噪声的影响是难以忽略的。因此，如何设计在噪声影响下依然鲁棒（robust）的量子算法对于量子计算的实用化来说是至关重要的。利用 Paddle Quantum 中的噪声模块，我们现在可以在设计并模拟量子算法的同时研究噪声对其的影响，从而进一步的探索对应的错误缓释（error mitigation）方案。\n",
    "\n",
    "## Paddle Quantum 中的噪声建模\n",
    "\n",
    "### 噪声模型与量子信道\n",
    "\n",
    "对于一个封闭的量子系统，其演化总是幺正（unitary）的。数学上，我们通常用酉变换的语言来描述一个参数化量子电路 $U(\\vec{\\theta})$ 的作用， \n",
    "\n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}) \\rho U^\\dagger(\\vec{\\theta}),\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "其中 $\\rho$ 表示初始量子态， $\\vec{\\theta}$ 表示电路的参数向量。那么最简单的一类噪声模型，是我们在控制量子系统执行具体逻辑门的时候参数的噪声化，\n",
    "\n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}+\\vec{\\epsilon}) \\rho U^\\dagger(\\vec{\\theta}+\\vec{\\epsilon}),\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "其中 $\\vec{\\epsilon}$ 可以是从高斯分布中采样出的白噪声。这样的噪声被称为**相干噪声（coherent noise）**，通常是由于硬件系统没有校准或者量子控制层面的误差。在某些特定情况下，相干噪声会比非相干噪声更具有破坏性 [1]。此外，值得注意的是相干噪声的建模也是用酉变换的语言 $U(\\vec{\\epsilon})$ 来描述的。\n",
    "\n",
    "相比于相干噪声，人们更为关注的问题是**开放系统**中的产生的非相干噪声，这样一个系统的演化往往是非幺正（non-unitary）的。这种情况下，我们需要通过一个更广义的映射来描述系统的演化，即 $\\rho \\longrightarrow \\mathcal{E}(\\rho)$，这种映射也被称之为一个**量子信道（quantum channel）**。为了方便讨论，我们这里采用 *operator-sum representation* [2] 将一个量子信道表示为\n",
    "\n",
    "$$\n",
    "\\mathcal{E}(\\rho) =  \\sum_{k=0}^{m-1} E_k \\rho E_k^{\\dagger},\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "其中 $\\{E_k\\}$ 被称为 *Kraus* 算符，同时还满足完备性条件 $\\sum_k E_k^\\dagger E_k = I$。注意到，量子信道数学上是 completely positive 和 trace-preserving 的。\n",
    "\n",
    "\n",
    "利用这种表示方法，我们可以直观的理解非相干噪声是如何影响量子态的：对于一个一开始处于纯态 $\\rho = |\\psi\\rangle\\langle \\psi|$ 的量子系统，经过一个噪声量子信道（例如 $m = 2$ ）时，我们将得到一个混态 $\\mathcal{E}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger$。以简单的单个量子比特上的比特反转（bit flip）噪声为例，其表达形式为\n",
    "\n",
    "$$\n",
    "\\mathcal{E}_{BF}(\\rho) = (1 - p) I \\rho I+ p X \\rho X,\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "其中 $X,I$ 是泡利矩阵。 对应的 *Kruas* 算符为：\n",
    "\n",
    "$$\n",
    "E_0 = \\sqrt{1-p}\n",
    "\\begin{bmatrix}\n",
    "1 &0 \\\\\n",
    "0& 1 \n",
    "\\end{bmatrix},\n",
    "E_1 = \\sqrt{p}\n",
    "\\begin{bmatrix}\n",
    "0& 1 \\\\\n",
    "1&0\n",
    "\\end{bmatrix}.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
    "该信道的物理含义可以理解为存在 $p$ 的概率将 $|0\\rangle$ 态反转到 $|1\\rangle$ 态上，反之亦然。在 Paddle Quantum 中，可以通过 `UAnsatz.bit_flip(p, which_qubit)` 来添加该信道，其中 `p` 代表噪声大小。\n",
    "\n",
    "**注释：** 对于一个量子信道，其 *Kraus* 算符表示未必是唯一的 [3]。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Paddle Quantum 中添加信道的方式\n",
    "\n",
    "接下来我们以比特反转信道为例，展示如何用 Paddle Quantum 中的噪声模块来实现对噪声的模拟。首先，将一个量子比特初始化为 $|0\\rangle$ 态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:16:08.247239Z",
     "start_time": "2021-04-08T05:16:08.036136Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEDCAYAAAA4FgP0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAUJ0lEQVR4nO3df7RdZX3n8fcn4aeC2kqslCSE1jAOWkEbkamdFhUcsAparYJA1aLpjKCyap3ijEXFds1Uq7OGAZzG8XdXwR9VJ6MU2lFpp1qVoPww0WhEkCCMoAgoUxH8zh97Rw6Xe8/dhLv3lbvfr7XOytnPfs4+32Rl3c/dz7P3s1NVSJLGa9liFyBJWlwGgSSNnEEgSSNnEEjSyBkEkjRyBoEkjdwui13AfbXPPvvUmjVrFrsMSXpAufTSS2+qqhWz7XvABcGaNWvYtGnTYpchSQ8oSa6Za59DQ5I0cgaBJI2cQSBJI2cQSNLIGQSSNHK9BUGSdyX5TpIvz7E/Sc5Ksi3JFUme0FctkqS59XlG8B7gqCn7jwbWtq/1wNt7rEWSNIfegqCq/gH43pQuxwLvq8bngIcl2beveiRJs1vMG8r2A66d2N7etl0/s2OS9TRnDaxevXqnv3DN6Z/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1J0sgZBJI0cgaBJI2cQSBJI2cQSNLIGQSSNHIGgSSN3P8Ha5RN+ccmpTsAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "{'0': 1024}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import paddle\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "\n",
    "# 设置量子比特数\n",
    "num_qubits = 1\n",
    "\n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(num_qubits)\n",
    "\n",
    "# 制备 |0> 态\n",
    "init_state = cir.run_density_matrix()\n",
    "\n",
    "# 进行计算基上测量，默认 shots=1024\n",
    "cir.measure(plot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之后，我们加上一个 $p=0.1$ 的比特反转噪声，并测量通过信道之后的量子比特。 \n",
    "**注释：** 噪声信道只支持在 density matrix 模式下运行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:16:09.221527Z",
     "start_time": "2021-04-08T05:16:08.977847Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEDCAYAAAA4FgP0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAToUlEQVR4nO3df7RdZX3n8fcn4acSbWtSayEQWkOdaAVtSp3aaVHBgaqgo7X8smpROqNRWa1Occaiol1jtTqrDsEl1vqrqyBatalSaEel02qrBOWHAaMRg4AyDYqAMorgd/7YO3C43HvuDsnel9z9fq11Vs7e+zn7fJOVdT93P8/ez5OqQpI0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D3hVe2vpzwN/BHyurWVy8Hdmu5OAU5JcDmyiWVdC2iW8a0ij0d61cy7wrKr6wnztpbEwCCRp5OwakqSRMwgkaeQMAkkaOYNAkkbOIJCkkTMIJGnkDAJJGrn/D/5KL0jCQu+6AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "经过了 bit flip 信道之后的量子态是：\n",
      " [[0.9+0.j 0. +0.j]\n",
      " [0. +0.j 0.1+0.j]]\n"
     ]
    }
   ],
   "source": [
    "# 噪声水平\n",
    "p = 0.1\n",
    "\n",
    "# 添加比特反转信道\n",
    "cir.bit_flip(p, 0)\n",
    "\n",
    "# 执行电路\n",
    "# 注释：噪声信道只能在 density matrix 模式下运行\n",
    "fin_state = cir.run_density_matrix()\n",
    "\n",
    "# 测量结果\n",
    "cir.measure(plot=True)\n",
    "print('经过了 bit flip 信道之后的量子态是：\\n', fin_state.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，经过了比特反转信道（概率为 $p=0.1$）之后的量子态变成了混合态 $0.9 | 0 \\rangle \\langle 0 | + 0.1 | 1 \\rangle \\langle 1 |$。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 常用噪声信道\n",
    "\n",
    "除了比特反转信道之外，Paddle Quantum 也支持模拟其他常用的噪声信道。\n",
    "\n",
    "\n",
    "- **相位反转信道（Phase Flip Channel）**\n",
    "\n",
    "  与比特反转信道类似，相位反转信道会以 $p$ 的概率来反转一个量子比特的相位，其表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PF}(\\rho) =  (1 - p) \\rho + p Z \\rho Z.\n",
    "  \\tag{6}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **比特相位反转信道（Bit-Phase Flip Channel）**\n",
    "\n",
    "  $$\n",
    "  \\mathcal{E}_{BPF}(\\rho) = (1-p) \\rho + p Y \\rho Y.\n",
    "  \\tag{7}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **去极化信道 （Depolarizing Channel）**\n",
    "\n",
    "  通过去极化信道之后，将会有 $p$ 的概率处于最大混态 $I/2$ 和 $1-p$ 的概率维持不变。可以表示为对称地施加泡利噪声，\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{D}(\\rho) = (1 - p) \\rho + \\frac{p}{3}\n",
    "  \\left( X \\rho X+ Y \\rho Y + Z \\rho Z \\right).\n",
    "  \\tag{8}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **泡利信道（Pauli Channel）**\n",
    "\n",
    "    该信道会以非对称的形式施加泡利噪声。表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{Pauli}(\\rho) = (1 - p_x - p_y - p_z) \\rho + p_x X \\rho X + p_y Y \\rho Y + p_z Z \\rho Z.\n",
    "  \\tag{9}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **振幅阻尼信道（Amplitude Damping Channel）**\n",
    "\n",
    "  振幅阻尼信道可以用来模拟当系统受到**能量耗散**时引入的噪声。表达形式为，\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{AD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{10}\n",
    "  $$\n",
    "  \n",
    "  其中 $\\gamma$ 表示耗散系数，\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix},\n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & \\sqrt{\\gamma} \\\\ 0 & 0\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{11}\n",
    "  $$ \n",
    "\n",
    "\n",
    "- **相位阻尼信道（Phase Damping Channel）**\n",
    "\n",
    "  相位阻尼信道描述的是当系统没有与外界环境交换能量，却损失了**量子信息**的情况下的噪声模型。其表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{12}\n",
    "  $$\n",
    "  \n",
    "  其中 $\\gamma$ 表示损失系数，\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix}, \n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & 0 \\\\ 0 & \\sqrt{\\gamma}\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{13}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **广义振幅阻尼信道（Generalized Amplitude Damping Channel）**\n",
    "\n",
    "  该信道描述的是系统与外界环境在**有限温度下交换能量**的噪声模型，同时也是**超导量子计算中的常见噪声** [4]。其表达形式较为复杂，感兴趣的读者可以进一步的阅读 [API 文档](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html) 和相应的参考文献。\n",
    "\n",
    "\n",
    "**注释：** 在 Paddle Quantum 中，我们可以通过 `UAnsatz.phase_flip()`，`UAnsatz.bit_phase_flip()`， `UAnsatz.depolarizing()`，`UAnsatz.pauli_channel()`, `UAnsatz.amplitude_damping()`，`UAnsatz.phase_damping()`以及 `UAnsatz.generalized_amplitude_damping()` 来添加上述噪声。\n",
    "\n",
    "**注释：** 通常会选择振幅阻尼信道和相位阻尼信道来建模实际量子设备中的噪声，因为这两种信道可以较好的描述真实量子系统中的物理过程（可以用来建模 $T_1$ 和 $T_2$ 噪声）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 自定义信道\n",
    "\n",
    "此外，我们也可以通过 `UAnsatz.customized_channel()` 来向电路中添加自定义噪声。具体的，该方法支持用自定义的 *Kraus* 算符来建模任意的噪声模型，我们自定义的方式来搭建比特反转信道为例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:17:30.681411Z",
     "start_time": "2021-04-08T05:17:30.658883Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "经过了自定义信道之后的量子态是：\n",
      " [[0.9+0.j 0. +0.j]\n",
      " [0. +0.j 0.1+0.j]]\n",
      "\n",
      "经过了比特反转信道之后的量子态是：\n",
      " [[0.9+0.j 0. +0.j]\n",
      " [0. +0.j 0.1+0.j]]\n",
      "\n",
      "两个态是否相同？ True\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "import numpy as np\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "\n",
    "# 设置噪声参数\n",
    "p = 0.1\n",
    "\n",
    "# 我们用自定义的 Kraus 算符来描述一个比特反转信道\n",
    "# 注意 Kraus 算符的数据类型应为 complex_128\n",
    "e_0 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[1, 0], [0, 1]], dtype='complex128'))\n",
    "e_1 = paddle.to_tensor(np.sqrt(p) * np.array([[0, 1], [1, 0]], dtype='complex128'))\n",
    "Kraus_ops = [e_0, e_1]\n",
    "\n",
    "# 初始化量子电路\n",
    "num_qubits = 1\n",
    "cir = UAnsatz(num_qubits)\n",
    "\n",
    "# 添加自定义噪声，其输入为 Kraus 算符的列表\n",
    "cir.customized_channel(Kraus_ops, 0)\n",
    "\n",
    "# 执行电路\n",
    "fin_state = cir.run_density_matrix()\n",
    "\n",
    "# 比较结果\n",
    "cir_1 = UAnsatz(num_qubits)\n",
    "cir_1.bit_flip(p, 0)\n",
    "fin_state_1 = cir_1.run_density_matrix()\n",
    "print('经过了自定义信道之后的量子态是：\\n', fin_state.numpy())\n",
    "print('\\n经过了比特反转信道之后的量子态是：\\n', fin_state_1.numpy())\n",
    "print('\\n两个态是否相同？', bool((fin_state - fin_state_1).abs().sum() < 1e-8))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "按照上述例子，用户可以通过自定义 *Kraus* 算符的方式实现特定的信道。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 拓展：Paddle Quantum 模拟含噪纠缠资源\n",
    "\n",
    "\n",
    "许多重要的量子技术，例如量子隐形传态、态转换、分布式量子计算等都需要纠缠资源的预先分配。以纠缠量子比特对为例，在理想情况下，我们希望分配的纠缠资源处于**最大纠缠态**（Maximally entangled state)。但是在实际的应用中，纠缠资源往往在制备、传输以及保存的过程中会和环境发生相互作用，从而引入噪声。下面，我们用 Paddle Quantum 中的去极化信道来模拟一个简单的场景，白噪声对贝尔态的影响："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:24:35.552425Z",
     "start_time": "2021-04-08T05:24:35.519733Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "初态和贝尔态之间的保真度为 1\n",
      "经过了传输（去极化信道）之后的纠缠对和贝尔态的保真度为 0.81333\n",
      "又经过了存储（振幅阻尼信道）之后的纠缠对和贝尔态的保真度为 0.66752\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "from paddle import matmul, trace\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "from paddle_quantum.state import bell_state\n",
    "\n",
    "# 噪声参数\n",
    "p_trans = 0.1\n",
    "p_store = 0.01\n",
    "\n",
    "# 创建用来模拟噪声的量子电路\n",
    "num_qubits = 2\n",
    "cir = UAnsatz(num_qubits)\n",
    "\n",
    "# 这里的初态是制备好的贝尔态\n",
    "init_state = paddle.to_tensor(bell_state(2))\n",
    "\n",
    "# 分别在两个量子比特上添加去极化信道，表示在传输过程中引入的噪声\n",
    "cir.depolarizing(p_trans, 0)\n",
    "cir.depolarizing(p_trans, 1)\n",
    "\n",
    "# 用模拟噪声的电路来演化该初态\n",
    "status_mid = cir.run_density_matrix(init_state)\n",
    "\n",
    "# 分别在两个量子比特上添加振幅阻尼信道，表示在保存过程中引入的噪声\n",
    "cir.amplitude_damping(p_store, 0)\n",
    "cir.amplitude_damping(p_store, 1)\n",
    "\n",
    "# 用模拟噪声的电路来演化该初态\n",
    "status_fin = cir.run_density_matrix(status_mid)\n",
    "fidelity_mid = paddle.real(trace(matmul(init_state, status_mid)))\n",
    "fidelity_fin = paddle.real(trace(matmul(init_state, status_fin)))\n",
    "\n",
    "print(\"初态和贝尔态之间的保真度为\", 1)\n",
    "print(\"经过了传输（去极化信道）之后的纠缠对和贝尔态的保真度为 {:.5f}\".format(fidelity_mid.numpy()[0]))\n",
    "print(\"又经过了存储（振幅阻尼信道）之后的纠缠对和贝尔态的保真度为 {:.5f}\".format(fidelity_fin.numpy()[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**注释：** 在 [纠缠蒸馏](../locc/EntanglementDistillation_LOCCNET_CN.ipynb) 的教程中我们介绍了如何利用 Paddle Quantm 中的 LoccNet 模块来研究纠缠蒸馏，即利用多个含噪声的纠缠对来提取高保真度的纠缠对，感兴趣的读者可以前往阅读。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 应用： Paddle Quantum 模拟含噪变分量子本征求解器（VQE）\n",
    "\n",
    "\n",
    "变分量子本征求解器（Variational Quantum Eigensolver）[5] 可以用变分量子电路来计算某个给定哈密顿量的基态能量，关于其具体的原理和背景在之前的教程 [变分量子本征求解器](../quantum_simulation/VQE_CN.ipynb) 中有详细的讲解，感兴趣的读者可以前往阅读。\n",
    "\n",
    "在这里，我们尝试用一个简单的 VQE 电路来求解如下哈密顿量的基态能量：\n",
    "\n",
    "$$ \n",
    "H = 0.4 \\, Z \\otimes I + 0.4 \\, I \\otimes Z + 0.2 \\, X \\otimes X. \n",
    "\\tag{14}\n",
    "$$\n",
    "\n",
    "特别地，我们将在电路中引入振幅阻尼信道来模拟电路运行时的 $T_1$ 噪声，让我们分别来看一下含噪电路和非含噪电路在该任务上的表现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:34:47.301281Z",
     "start_time": "2021-04-08T05:34:47.293619Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import paddle\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "from paddle_quantum.utils import pauli_str_to_matrix\n",
    "\n",
    "# 首先生成泡利字符串表示下的哈密顿量\n",
    "H_info = [[0.4, 'z0'], [0.4, 'z1'], [0.2, 'x0,x1']]\n",
    "\n",
    "# 把记录的关于哈密顿量的信息转化为矩阵表示\n",
    "H_matrix = pauli_str_to_matrix(H_info, num_qubits)\n",
    "\n",
    "# 超参数设置\n",
    "num_qubits = 2\n",
    "theta_size = 4\n",
    "ITR = 100\n",
    "LR = 0.4\n",
    "SEED = 999    \n",
    "p = 0.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:34:51.742273Z",
     "start_time": "2021-04-08T05:34:47.726698Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========== Training Noisy VQE ==========\n",
      "iter: 0   loss: -0.0782\n",
      "iter: 10   loss: -0.6395\n",
      "iter: 20   loss: -0.6548\n",
      "iter: 30   loss: -0.6547\n",
      "iter: 40   loss: -0.6591\n",
      "iter: 50   loss: -0.6608\n",
      "iter: 60   loss: -0.6618\n",
      "iter: 70   loss: -0.6621\n",
      "iter: 80   loss: -0.6621\n",
      "iter: 90   loss: -0.6621\n",
      "========== Training Noise Free VQE ==========\n",
      "iter: 0   loss: 0.1521\n",
      "iter: 10   loss: -0.7413\n",
      "iter: 20   loss: -0.8208\n",
      "iter: 30   loss: -0.8170\n",
      "iter: 40   loss: -0.8169\n",
      "iter: 50   loss: -0.8241\n",
      "iter: 60   loss: -0.8238\n",
      "iter: 70   loss: -0.8245\n",
      "iter: 80   loss: -0.8245\n",
      "iter: 90   loss: -0.8246\n",
      "\n",
      "含噪电路计算得到的基态能量是:  -0.6621559864367315 Ha\n",
      "不含噪电路计算得到的基态能量是:  -0.8246026782552648 Ha\n",
      "真实的基态能量为:  -0.8246211251235321 Ha\n"
     ]
    }
   ],
   "source": [
    "class vqe_noisy(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self, shape, dtype='float64'):\n",
    "        super(vqe_noisy, self).__init__()\n",
    "        \n",
    "        # 初始化一个长度为theta_size的可学习参数列表，并用[0, 2*pi]的均匀分布来填充初始值\n",
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=0., high=2*np.pi), \n",
    "                                           dtype=dtype, is_bias=False)\n",
    "        \n",
    "    # 定义损失函数和前向传播机制\n",
    "    def forward(self):\n",
    "        \n",
    "        # 初始量子电路\n",
    "        cir = UAnsatz(num_qubits)\n",
    "        \n",
    "        # 添加参数化量子电路\n",
    "        cir.ry(self.theta[0], 0)\n",
    "        cir.ry(self.theta[1], 1)\n",
    "        \n",
    "        cir.cnot([0, 1])\n",
    "        \n",
    "        cir.ry(self.theta[2], 0)\n",
    "        cir.ry(self.theta[3], 1)\n",
    "        \n",
    "        # 添加振幅阻尼 AD 噪声\n",
    "        cir.amplitude_damping(p, 0)\n",
    "        cir.amplitude_damping(p, 1)\n",
    "        \n",
    "        # 运行密度矩阵模式\n",
    "        cir.run_density_matrix()\n",
    "        \n",
    "        # 关于观测量 H_info 的期望值\n",
    "        loss = cir.expecval(H_info)\n",
    "        \n",
    "        return loss\n",
    "    \n",
    "# 创建一个不含噪声的 VQE 电路\n",
    "class vqe_noise_free(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self, shape, dtype='float64'):\n",
    "        super(vqe_noise_free, self).__init__()\n",
    "        \n",
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=0., high=2*np.pi), \n",
    "                                           dtype=dtype, is_bias=False)\n",
    "        \n",
    "    def forward(self):\n",
    "        \n",
    "        cir = UAnsatz(num_qubits)\n",
    "        cir.ry(self.theta[0], 0)\n",
    "        cir.ry(self.theta[1], 1) \n",
    "        cir.cnot([0, 1])\n",
    "        cir.ry(self.theta[2], 0)\n",
    "        cir.ry(self.theta[3], 1)\n",
    "        cir.run_density_matrix()\n",
    "        loss = cir.expecval(H_info)\n",
    "        \n",
    "        return loss\n",
    "    \n",
    "# 训练含噪 VQE 电路\n",
    "print('========== Training Noisy VQE ==========')\n",
    "loss_list = []\n",
    "parameter_list = []\n",
    "\n",
    "# 定义参数维度\n",
    "vqe = vqe_noisy([theta_size])\n",
    "\n",
    "# 一般来说，我们利用Adam优化器来获得相对好的收敛，当然你可以改成SGD或者是RMS prop.\n",
    "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe.parameters())    \n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 前向传播计算损失函数\n",
    "    loss = vqe()\n",
    "\n",
    "    # 反向传播极小化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 记录学习曲线\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(vqe.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "        \n",
    "# 用同样的方式训练不含噪的 VQE 电路\n",
    "print('========== Training Noise Free VQE ==========')\n",
    "loss_list_no_noise = []\n",
    "parameter_list_no_noise = []\n",
    "\n",
    "vqe_no_noise = vqe_noise_free([theta_size])\n",
    "opt_no_noise = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe_no_noise.parameters())    \n",
    "\n",
    "for itr in range(ITR):\n",
    "\n",
    "    loss = vqe_no_noise()\n",
    "\n",
    "    loss.backward()\n",
    "    opt_no_noise.minimize(loss)\n",
    "    opt_no_noise.clear_grad()\n",
    "\n",
    "    loss_list_no_noise.append(loss.numpy()[0])\n",
    "    parameter_list_no_noise.append(vqe_no_noise.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "\n",
    "\n",
    "print('\\n含噪电路计算得到的基态能量是: ', loss_list[-1], \"Ha\")\n",
    "print('不含噪电路计算得到的基态能量是: ', loss_list_no_noise[-1], \"Ha\")\n",
    "print('真实的基态能量为: ', np.linalg.eigh(H_matrix)[0][0], \"Ha\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，含噪的变分量子本征求解器的效果要差于不含噪的版本，无法达到化学精度的要求 $\\varepsilon = 0.0016$ Ha。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "噪声是 NISQ 时代量子设备的一个不可忽视的特征。在近期的量子技术中，我们有必要将噪声考虑进计算模型中。因此，设计对于噪声鲁棒的量子算法，乃至于设计噪声抑制方案，都是 NISQ 时代的一大重要方向。基于 Paddle Quantum 新增的噪声模块，我们希望为开发者提供贴近真实系统的近期量子计算应用的开发平台，帮助使用者一起思考如何更好地使用含噪量子设备以及如何设计出更鲁棒的量子算法，进而更好地通过近期量子设备实现人工智能、量子化学等领域的应用。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] Iverson, J. K., & Preskill, J. Coherence in logical quantum channels. [New Journal of Physics, 22(7), 073066 (2020).](https://iopscience.iop.org/article/10.1088/1367-2630/ab8e5c)\n",
    "\n",
    "[2] Nielsen, M. A. & Chuang, I. L. Quantum computation and quantum information. Cambridge university press (2010).\n",
    "\n",
    "[3] Preskill, J. Quantum Information Lecture Notes. Chapter 3 (2018).\n",
    "\n",
    "[4] Chirolli, L., & Burkard, G. Decoherence in solid-state qubits. [Advances in Physics, 57(3), 225-285 (2008).](https://www.tandfonline.com/doi/abs/10.1080/00018730802218067)\n",
    "\n",
    "[5] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
